<template>
  <el-row>
    <el-card>
      <el-form ref="searchForm" :inline="true" :model="searchForm">
        <el-form-item :label="$t('financeModule.list.detail.loanType')">
          <el-select v-model="searchForm.productType" clearable :placeholder="$t('financeModule.list.loanType')">
            <el-option
              v-for="item in $t('financeModule.list.type')"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('financeModule.repayList.tabData.createTime')">
          <el-date-picker
            v-model="time"
            type="daterange"
            range-separator="~"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"
          />
        </el-form-item>
        <el-form-item :label="$t('financeModule.repayList.tabData.repayShouldTime')">
          <el-date-picker
            v-model="planRepaymentTime"
            type="daterange"
            range-separator="~"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"
          />
        </el-form-item>
        <el-form-item :label="$t('financeModule.repayList.tabData.repay')">
          <el-select v-model="searchForm.paymentStatus" clearable :placeholder="$t('common.select')">
            <el-option
              v-for="(item, index) in $t('financeModule.repayList.repayStatus')"
              :key="index"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('financeModule.repayList.tabData.settle')">
          <el-select v-model="searchForm.endStatus" clearable :placeholder="$t('common.select')">
            <el-option
              v-for="(item, index) in $t('financeModule.repayList.settleStatus')"
              :key="index"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="inputData" :placeholder="$t('common.input')" class="input-with-select">
            <el-select slot="prepend" v-model="selectData">
              <el-option
                v-for="(item, index) in $t('financeModule.list.search')"
                :key="index"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-input>
        </el-form-item>
        <el-row>
          <el-button type="primary" @click="search">
            {{ $t('common.search') }}
          </el-button>
          <el-button @click="reset">
            {{ $t('common.reset') }}
          </el-button>
          <el-button :disabled="!(totalNumber > 0)" @click="exportList">
            {{ $t('common.ex') }}
          </el-button>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-table
        v-loading="loading"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="tableData"
        border
        :stripe="true"
        style="width: 100%;"
      >
        <el-table-column
          fixed="left"
          prop="orderNO"
          :label="tableText['orderNo']"
          min-width="170"
        />
        <el-table-column
          prop="createTimeStr"
          :label="tableText['createTime']"
          min-width="170"
        />
        <el-table-column
          prop="phoneNumber"
          :label="tableText['userAccount']"
          min-width="150"
        />
        <el-table-column
          prop="userName"
          :label="tableText['userName']"
          min-width="120"
        />
        <el-table-column
          prop="orderType"
          :label="tableText['type']"
          min-width="200"
        >
          <template slot-scope="scope">
            {{ setValue(scope.row['orderType']) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="totalPeriod"
          :label="tableText['periodsNumber']"
          min-width="100"
        >
          <template slot-scope="scope">
            {{ scope.row['currentPeriod'] && scope.row['totalPeriod'] ? scope.row['currentPeriod'] + ' / ' + scope.row['totalPeriod'] : '' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="currentRepay"
          :label="tableText['periodRepayShould']"
          min-width="200"
        >
          <template slot-scope="scope">
            {{ scope.row['currentRepay'] ? (scope.row['currentRepay']).toFixed(2) : 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="principal"
          :label="tableText['principal']"
          min-width="120"
        >
          <template slot-scope="scope">
            {{ scope.row['principal'] ? (scope.row['principal']).toFixed(2) : 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="interestMoney"
          :label="tableText['interest']"
          min-width="120"
        >
          <template slot-scope="scope">
            {{ scope.row['interestMoney'] ? (scope.row['interestMoney']).toFixed(2) : 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="serveCharge"
          :label="tableText['serviceFee']"
          min-width="200"
        >
          <template slot-scope="scope">
            {{ scope.row['serveCharge'] ? (scope.row['serveCharge']).toFixed(2) : 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="overDueFine"
          :label="tableText['overdueFee']"
          min-width="170"
        >
          <template slot-scope="scope">
            {{ scope.row['overDueFine'] ? (scope.row['overDueFine']).toFixed(2) : 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="planRepaymentDateStr"
          :label="tableText['repayShouldTime']"
          min-width="170"
        />
        <el-table-column
          prop="dueDays"
          :label="tableText['overdueDay']"
          min-width="150"
        />
        <el-table-column
          prop="realRepayMoney"
          :label="tableText['repayMount']"
          min-width="200"
        >
          <template slot-scope="scope">
            {{ scope.row['realRepayMoney'] ? scope.row['realRepayMoney'].toFixed(2) : 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="realRepaymentDateStr"
          :label="tableText['repayDate']"
          min-width="170"
        />
        <el-table-column
          fixed="right"
          prop="statusStr"
          :label="tableText['orderStatus']"
          min-width="120"
        />
        <el-table-column
          fixed="right"
          :label="$t('common.operate.name')"
          min-width="200"
        >
          <template slot-scope="scope">
            <el-button v-if="[1, 2, 3, 4, 5, 6, 11, 12, 13, 14].includes(scope.row.status)" :loading="operateLoading" size="small" @click="operate(scope.row)">{{ $t('common.operate.name') }}</el-button>
            <el-button size="small" @click="toDetail(scope.row)">{{ $t('common.btnGroup.a') }}</el-button>
          </template>
        </el-table-column>

      </el-table>
      <div class="block">
        <el-pagination
          :current-page="searchForm.currentPage"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="searchForm.pageSize"
          :total="totalNumber"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <repay-list-dialog
      :show-dialog="editDialog"
      :choose-item="chooseItem"
      :repay-method="repayMethod"
      :serial-number-data="serialNumberData"
      @change-dialog="changeDialog"
      @edit-success="editSuccess"
    />
  </el-row>
</template>

<script>
import { queryRepaymentManage, queryPaymentExport, manualRepaymentList } from '@/api/finance'
import { formatDate, ObjToQueryString } from '@/utils/method'
import RepayListDialog from '@/components/finance/repay-list-dialog'
export default {
  name: 'RepayList',
  components: {
    RepayListDialog
  },
  data() {
    return {
      loading: true,
      editDialog: false,
      operateLoading: false,
      time: null,
      planRepaymentTime: [new Date((new Date()).getTime() - 1000 * 60 * 60 * 24 * 6), new Date()],
      tableData: [],
      tableText: {},
      totalNumber: 0,
      searchForm: this.params(),
      inputData: null,
      selectData: 'orderNo',
      chooseItem: {
        currentRepay: null,
        description: null,
        isCancelRepayment: null,
        isDone: null,
        orderId: null,
        repayMoney: null,
        repayType: null,
        repaymentDate: null,
        serialNumber: null,
        loanType: null,
        money: null,
        repaymentPlanId: null,
        manualRepaymentId: null,
        realRepayMoney: null,
        userId: null,
        currentPeriod: null,
        totalPeriod: null,
        operator: 1,
        operationResult: 0
      },
      repayMethod: [],
      serialNumberData: []
    }
  },
  mounted() {
    this.tableText = this.$t('financeModule.repayList.tabData')
    this.getData()
  },
  methods: {
    search() {
      this.searchForm.currentPage = 1
      this.getData()
    },
    params() {
      return {
        currentPage: 1,
        pageSize: 10,
        productType: null,
        createTimeStart: null,
        createTimeEnd: null,
        planRepaymentTimeStart: null,
        planRepaymentTimeEnd: null,
        paymentStatus: '',
        endStatus: '',
        orderNo: null,
        phoneNumber: null,
        userName: null,
        id: null,
        columns: ['order_create_time'],
        orderBy: [false]
      }
    },
    reset() {
      this.searchForm = this.params()
      this.selectData = 'orderNo'
      this.inputData = null
      this.time = null
      this.planRepaymentTime = [new Date((new Date()).getTime() - 1000 * 60 * 60 * 24 * 6), new Date()]
      this.getData()
    },
    getData() {
      this.loading = true
      const data = this.searchData()
      queryRepaymentManage(data)
        .then(res => {
          this.loading = false
          if (res.success) {
            this.tableData = res.data
            this.totalNumber = res.page ? res.page['totalNumber'] : 0
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    exportList() {
      queryPaymentExport(this.searchData())
    },
    searchData() {
      const data = {
        currentPage: this.searchForm.currentPage,
        pageSize: this.searchForm.pageSize,
        productType: this.searchForm.productType,
        status: this.searchForm.status
      }
      if (this.time && this.time.length > 1) {
        data['createTimeStart'] = formatDate(new Date(this.time[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['createTimeEnd'] = formatDate(new Date(this.time[1]), 'yyyy-MM-dd') + ' 23:59:59'
      }
      if (this.planRepaymentTime && this.planRepaymentTime.length > 1) {
        data['planRepaymentTimeStart'] = formatDate(new Date(this.planRepaymentTime[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['planRepaymentTimeEnd'] = formatDate(new Date(this.planRepaymentTime[1]), 'yyyy-MM-dd') + ' 23:59:59'
      }
      if (this.selectData && this.inputData) {
        data[this.selectData] = this.inputData
      }
      return data
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.searchForm.currentPage = val
      this.getData()
    },
    toDetail(item) {
      const paramData = {
        orderId: item['orderId'],
        userId: item['userId']
      }
      const para = ObjToQueryString(paramData)
      window.open(`${window.location.origin + window.location.pathname}#/order/detail?${para}`, '_blank')
    },
    setValue(val) {
      const map = this.$t(`financeModule.list.type`)
      const name = map.filter(v => {
        return v['value'] === val
      })
      return name && name[0] && name[0]['desc'] ? name[0]['desc'] : ''
    },
    choose(param) {
      this.chooseItem.currentRepay = param.currentRepay
      this.chooseItem.description = param.description
      this.chooseItem.isCancelRepayment = param.isCancelRepayment
      this.chooseItem.isDone = param.isDone
      this.chooseItem.orderId = param.orderId
      this.chooseItem.repayMoney = param.repayMoney
      this.chooseItem.repayType = param.repayType
      this.chooseItem.repaymentDate = param.repaymentDate
      this.chooseItem.serialNumber = param.serialNumber
      this.chooseItem.loanType = param.loanType
      this.chooseItem.money = param.money
      this.chooseItem.repaymentPlanId = param.repaymentPlanId
      this.chooseItem.manualRepaymentId = param.manualRepaymentId
      this.chooseItem.realRepayMoney = param.realRepayMoney
      this.chooseItem.userId = param.userId
      this.chooseItem.currentPeriod = param.currentPeriod
      this.chooseItem.totalPeriod = param.totalPeriod
      this.chooseItem.operator = 1
      this.chooseItem.operationResult = 0
    },
    changeDialog(param) {
      this.editDialog = param
      setTimeout(() => {
        this.choose({})
      }, 10)
    },
    editSuccess() {
      this.getData()
    },
    operate(item) {
      this.operateLoading = true
      const params = {
        removeCancel: true
      }
      manualRepaymentList(item['orderId'], params)
        .then(res => {
          if (res.success) {
            this.serialNumberData = []
            if (res.data) {
              const obj = res.data.filter(v => {
                return v['isCancel'] === false
              })
              obj.forEach(v => {
                this.serialNumberData.push(
                  {
                    serialNumber: v['serialNumber'],
                    money: v['repayMoney'],
                    manualRepaymentId: v['id']
                  }
                )
              })
            }
            const data = {
              orderId: item['orderId'],
              repayMoney: item['currentLeft'] ? (item['currentLeft']).toFixed(2) : 0,
              realRepayMoney: item.realRepayMoney ? (item.realRepayMoney).toFixed(2) : 0,
              currentRepay: (item.realRepayMoney + item['currentLeft']) ? (item.realRepayMoney + item['currentLeft']).toFixed(2) : 0, // 应还
              isCancelRepayment: null, // 撤销还款
              repaymentPlanId: item.id,
              userId: item.userId,
              loanType: item.loanType,
              money: null, // 撤销还款金额
              isDone: null,
              repayType: null, // 还款方式,
              serialNumber: null, // 流水号
              description: null,
              manualRepaymentId: null,
              repaymentDate: null,
              currentPeriod: item.currentPeriod,
              totalPeriod: item.totalPeriod,
              operator: 1,
              operationResult: 0
            }
            if (this.serialNumberData.length > 0) {
              if ([4, 6, 12, 13, 14].includes(item.status)) {
                data['isDone'] = 1
                this.repayMethod = this.$t('financeModule.repayList.operType1')
              } else {
                data['isDone'] = true
                this.repayMethod = this.$t('financeModule.repayList.operType')
              }
            } else {
              if (item.status !== 9 && item.status !== 10) {
                data['isDone'] = false
                this.repayMethod = this.$t('financeModule.repayList.operType2')
              }
            }
            this.choose(data)
            this.editDialog = true
            this.operateLoading = false
          } else {
            this.operateLoading = false
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.operateLoading = false
          this.$message.error(err.message)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card{
  margin: 10px;
}
</style>
